package cn.easybuy.web.pre;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.easybuy.entity.Car;
import cn.easybuy.service.CarService;
import cn.easybuy.service.impl.CarServiceImpl;

public class BuyCarServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action=request.getParameter("action");
		PrintWriter out=response.getWriter();
		Car car=new Car();
		CarService cs=new CarServiceImpl();
		if (action.equals("addCar")) {
			
			//将加入的购物车的产品存了数据库
			//通过name查数据库，有 只更新数量，没有 直接增加
			String name=request.getParameter("name");
			String price=request.getParameter("price");
			String color=request.getParameter("color");
			String numberBuy=request.getParameter("numberBuy");
			car.setName(name);
			car.setShuxin("颜色："+color);
			List<Car> list=cs.getCarsByName(name);
			if (list.size()>0) { //该产品已在购物车
				for (Car car2 : list) {
					car.setNumber(car2.getNumber()+Integer.parseInt(numberBuy));
					car.setTotalPay(Double.parseDouble(price)*(car2.getNumber()+Integer.parseInt(numberBuy)));
				}
				cs.updataProduct(car);
			}else {
				car.setNumber(Integer.parseInt(numberBuy));
				car.setTotalPay(Double.parseDouble(price)*Integer.parseInt(numberBuy));
				cs.saveProduct(car);
			}
			
			out.print("ok");
		}else if (action.equals("showCar")) {
			List<Car> list=cs.getCarsAll();
			String carAllJSON=JSON.toJSONString(list);
			out.print(carAllJSON);
		}else if (action.equals("delCar")) {
			String name=request.getParameter("name");
			int num=cs.delProduct(name);
			if (num>0) {
				//删除成功则返回success
				out.print("success");
			}
			
		}
		out.flush();
		out.close();
		
	}

}
